import React, { useMemo, useState } from 'react';
import { View, StyleSheet, Switch } from 'react-native';
import { Layout, UI, useThemeColors, Loading } from '@gaozh1024/rn-toolkit';

type Mode = 'blocking' | 'semi';

const LoadingTestScreen: React.FC = () => {
    const colors = useThemeColors();

    const styles = StyleSheet.create({
        section: { marginBottom: 16 },
        row: { flexDirection: 'row', alignItems: 'center', gap: 12, flexWrap: 'wrap' },
        col: { gap: 12 },
        card: { borderRadius: 12, borderWidth: 1, borderColor: colors.border },
        bordered: { borderWidth: 1, borderColor: colors.border, borderRadius: 8, padding: 12 },
    });

    // 行为与样式配置
    const [mode, setMode] = useState<Mode>('blocking');
    const [cancelable, setCancelable] = useState<boolean>(false);
    const [maskColor, setMaskColor] = useState<string>('rgba(0,0,0,0.45)');
    const [animationDurationStr, setAnimationDurationStr] = useState<string>('200');

    // 文案
    const [message, setMessage] = useState<string>('加载中...');

    // 交互结果
    const [cancelCount, setCancelCount] = useState<number>(0);
    const [underlyingClickCount, setUnderlyingClickCount] = useState<number>(0);

    const animationDuration = useMemo(() => {
        const v = parseInt(animationDurationStr);
        return Number.isFinite(v) ? v : 200;
    }, [animationDurationStr]);

    const showLoading = (m: Mode) => {
        Loading.show({
            message,
            mode: m,
            cancelable,
            onCancel: () => setCancelCount((n) => n + 1),
            maskColor,
            animationDuration,
        });
    };

    const autoHide = () => {
        showLoading(mode);
        setTimeout(() => Loading.hide(), 1200);
    };

    return (
        <Layout.Page
            headerShown
            headerProps={{ title: 'Loading 测试', backVisible: true }}
            padding={16}
            scrollable
            testID="LoadingTestScreen"
        >
            {/* 行为与样式 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>行为与样式</UI.Text>
                    <View style={styles.col}>
                        <UI.Text children={'消息文案（message）'} />
                        <UI.Input
                            value={message}
                            onChangeText={setMessage}
                            placeholder="加载中..."
                            testID="input-message"
                        />
                        <UI.Text children={'遮罩颜色（maskColor）'} />
                        <UI.Input
                            value={maskColor}
                            onChangeText={setMaskColor}
                            placeholder="rgba(0,0,0,0.45)"
                            testID="input-mask-color"
                        />
                        <UI.Text children={'动画时长（ms）'} />
                        <UI.Input
                            value={animationDurationStr}
                            onChangeText={setAnimationDurationStr}
                            placeholder="200"
                            keyboardType="numeric"
                            testID="input-animation-duration"
                        />
                    </View>
                    <View style={[styles.row, { marginTop: 12 }]}>
                        <UI.Button
                            title="模式：阻塞（blocking）"
                            variant={mode === 'blocking' ? 'primary' : 'outline'}
                            onPress={() => setMode('blocking')}
                            testID="btn-mode-blocking"
                        />
                        <UI.Button
                            title="模式：半阻断（semi）"
                            variant={mode === 'semi' ? 'primary' : 'outline'}
                            onPress={() => setMode('semi')}
                            testID="btn-mode-semi"
                        />
                        <UI.Text variant="body2" color="textSecondary">可取消（cancelable）</UI.Text>
                        <Switch value={cancelable} onValueChange={setCancelable} testID="switch-cancelable" />
                    </View>
                </Layout.Card>
            </View>

            {/* 基础用法 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>基础用法</UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="显示（阻塞）" onPress={() => showLoading('blocking')} fullWidth testID="btn-show-blocking" />
                        <UI.Button title="显示（半阻断）" onPress={() => showLoading('semi')} fullWidth testID="btn-show-semi" />
                    </View>
                    <View style={[styles.row, { marginTop: 12 }]}>
                        <UI.Button title="显示后自动隐藏（1.2s）" variant="outline" onPress={autoHide} fullWidth testID="btn-auto-hide" />
                        <UI.Button title="隐藏" variant="outline" onPress={() => Loading.hide()} fullWidth testID="btn-hide" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="caption" color="subtext" mb={8}>取消回调次数（onCancel）：</UI.Text>
                        <UI.Text variant="body1" color="text" testID="text-cancel-count">{cancelCount}</UI.Text>
                    </View>
                </Layout.Card>
            </View>

            {/* 取消行为与穿透测试 */}
            <View style={styles.section}>
                <Layout.Card style={styles.card} p={16} backgroundColor={colors.surface}>
                    <UI.Text variant="h3" color="text" style={{ marginBottom: 12 }}>取消行为与穿透</UI.Text>
                    <UI.Text variant="caption" color="subtext" mb={8}>
                        blocking 模式下遮罩可点击取消（需 cancelable=true）；semi 模式下中心卡片显示“取消”按钮且遮罩穿透，底层按钮仍可点击。
                    </UI.Text>
                    <View style={styles.row}>
                        <UI.Button title="显示阻塞 + 遮罩可取消" onPress={() => { setCancelable(true); showLoading('blocking'); }} fullWidth testID="btn-show-blocking-cancelable" />
                        <UI.Button title="显示半阻断 + 中心取消按钮" onPress={() => { setCancelable(true); showLoading('semi'); }} fullWidth testID="btn-show-semi-cancelable" />
                    </View>
                    <View style={[styles.row, { marginTop: 12 }]}>
                        <UI.Button title="底层按钮（计数+1）" onPress={() => setUnderlyingClickCount((n) => n + 1)} fullWidth testID="btn-underlying" />
                    </View>
                    <View style={[styles.bordered, { marginTop: 12 }]}>
                        <UI.Text variant="body1" color="text" testID="text-underlying-count">底层点击计数：{underlyingClickCount}</UI.Text>
                    </View>
                </Layout.Card>
            </View>
        </Layout.Page>
    );
};

export default LoadingTestScreen;